package com.kingsystem.kingteachermarks_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingsystem.kingteachermarks_backend.entity.Dept;
import com.kingsystem.kingteachermarks_backend.mapper.DeptMapper;
import com.kingsystem.kingteachermarks_backend.service.impl.DeptServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author leiyue_yao
 * @since 2025-05-22
 */
@Controller
@RequestMapping("/dept")
@CrossOrigin
public class DeptController {

    @Autowired
    private DeptMapper dm;


    @PostMapping("/getDeptsByParentDeptId")
    @ResponseBody
    @ApiOperation(value="根据父部门id获取下级部门信息", notes = "根据父部门id获取下级部门信息")
    public List<Dept> getDeptsByParentDeptId(@RequestParam("parentDeptId") String parentDeptId){

        QueryWrapper<Dept> qw = new QueryWrapper<>();

        if(!parentDeptId.isEmpty()){
            qw.eq("parent_dept_id", parentDeptId);
        }
        List<Dept> li = dm.selectList(qw);

        return li;
    }

    @RequestMapping("/getAllDepts")
    @ResponseBody
    public List<Dept> getAllDepts() {
        QueryWrapper<Dept> qw =new QueryWrapper<>();
        qw.orderByAsc("sort");
        return dm.selectList(null);
    }

    @RequestMapping("/addDept")
    @ResponseBody
    public String addDept(@RequestBody Dept dept) {
        try{
            dm.insert(dept);
            return "success";
        }
        catch(Exception e){
            return e.getMessage();
        }
    }

    @PostMapping("/delDeptById")
    @ResponseBody
    public String delDeptById(@RequestParam("deptId") String deptId){
        try {
            QueryWrapper<Dept> qw = new QueryWrapper<>();
            qw.eq("TableKey", deptId);
            dm.delete(qw);
            return "success";
        }
        catch(Exception e){
            return e.getMessage();
        }
    }

    @RequestMapping("/editDept")
    @ResponseBody
    public String editDept(@RequestBody Dept dept) {
        try{
            dm.updateById(dept);
            return "success";
        }
        catch(Exception e){
            return e.getMessage();
        }
    }
}
